package com.zsy.controller;

import com.zsy.pojo.R;
import com.zsy.pojo.User;
import com.zsy.service.UserService;
import com.zsy.utils.SMSUtils;
import com.zsy.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserService userService;


    @RequestMapping("/sendMsg")
    public R<String> login(@RequestBody User user) {
        //获取手机号
        String phone = user.getPhone();
        //调用工具类
        String code = ValidateCodeUtils.generateValidateCode(6).toString();

        /*  SMSUtils.sendMessage("黑马旅游网","SMS_205126318",phone,code);*/
        log.info("=================验证码是:" + code);

        redisTemplate.opsForValue().set(phone, code, 1, TimeUnit.MINUTES);

        return R.success("验证码发送成功");
    }

    @RequestMapping("/login")
    public R<String> login(@RequestBody Map<String, String> param, HttpSession session) {
        String phone = param.get("phone");
        String code = param.get("code");
        String codeInSession = (String) redisTemplate.opsForValue().get(phone);

        User user = userService.login(phone, code, codeInSession);
        if (user != null) {
            redisTemplate.delete(phone);
            session.setAttribute("user", user.getId());
        } else {
            return R.error("登录失败");
        }
        return R.success("登录成功");
    }

    @PostMapping("loginout")
    public R<String> loginout(HttpSession session) {
        session.invalidate();
        return R.success("退出成功");
    }

}
